package com.dragon.concurrent.demo.deadlock;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

/**
 * @author dragon
 * @version V1.0.0-RELEASE
 * @date 2019/6/5 12:03
 */
public class DeadLockChecker {
    private final static ThreadMXBean mbean = ManagementFactory.getThreadMXBean();

    final static Runnable deadlockCheck = () -> {
        while (true) {
            long[] deadlockedThreadIds = mbean.findDeadlockedThreads();
            if (deadlockedThreadIds != null) {
                ThreadInfo[] threadInfos = mbean.getThreadInfo(deadlockedThreadIds);
                for (Thread t : Thread.getAllStackTraces().keySet()) {
                    for (int i = 0; i < threadInfos.length; i++) {
                        if (t.getId() == threadInfos[i].getThreadId()) {
                            t.interrupt();
                        }
                    }
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public static void check() {
        Thread thread = new Thread(deadlockCheck);
        thread.setDaemon(true);
        thread.start();
    }
}
